package online.dgyj.gateway;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.nle.mylibrary.claimer.connector.ConnectorListener;
import com.nle.mylibrary.databus.DataBusFactory;
import com.nle.mylibrary.device.GenericConnector;
import com.nle.mylibrary.device.listener.ConnectResultListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Handler handler = new Handler(Looper.getMainLooper());
    String gatewayIP;    // 中心网关IP
    int gatewayPort; // 中心网关端口
    GenericConnector genericConnector;  // 定义一个通用连接器对象
    boolean searchTag = false;  // 获取方式标志 false 为主动上报 true 为被动上报
    boolean accessTag = false;  // 获取方式标志 false 为单次获取 true 为持续获取
    Thread getSensorDataThread;   // 获取数据子线程

    // 定义视图控件
    EditText GateWayPortEdit, GateWayIPEdit, SensorTagEdit, ControlTagEdit, ControlValueEdit;
    TextView SensorValueText;
    Button LinkButton, GetButton, SendButton;
    RadioGroup AccessRadioGroup;
    RadioButton GetSingleButton, GetContinuousButton;
    Switch SearchSwitch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        bind(); // 实例化控件并绑定事件处理
    }

    /**
     * 实例化控件
     */
    void bind() {
        GateWayPortEdit = findViewById(R.id.GateWayPortEdit);
        GateWayIPEdit = findViewById(R.id.GateWayIPEdit);
        SensorTagEdit = findViewById(R.id.SensorTagEdit);
        ControlTagEdit = findViewById(R.id.ControlTagEdit);
        ControlValueEdit = findViewById(R.id.ControlValueEdit);

        SensorValueText = findViewById(R.id.SensorValueText);

        LinkButton = findViewById(R.id.LinkButton);
        GetButton = findViewById(R.id.GetButton);
        SendButton = findViewById(R.id.SendButton);

        AccessRadioGroup = findViewById(R.id.AccessRadioGroup);
        GetSingleButton = findViewById(R.id.GetSingleButton);
        GetContinuousButton = findViewById(R.id.GetContinuousButton);

        SearchSwitch = findViewById(R.id.SearchSwitch);

        // Button绑定点击事件处理
        LinkButton.setOnClickListener(this);
        GetButton.setOnClickListener(this);
        SendButton.setOnClickListener(this);

        // SensorData长按清楚显示数据
        SensorValueText.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        SensorValueText.setText("NULL");
                    }
                });
                return false;
            }
        });

        // 绑定Radio事件处理 (数据获取方式:单次获取/持续获取)
        AccessRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.GetSingleButton)
                    accessTag = false;
                else if (checkedId == R.id.GetContinuousButton)
                    accessTag = true;
            }
        });
    }

    /**
     * 获取中心网关数据
     * 主动上报方式
     *
     * @return 子线程
     */
    Thread GetGateWayResultDataThread() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        // 输出主动上报数据
                        Log.i("Data", genericConnector.GateWayData(genericConnector.getGateWayResultData().getBytes()));
                        // 将传感器数据显示在SetSensorDataValue
                        SetSensorDataValue(genericConnector.GateWayData(genericConnector.getGateWayResultData().getBytes()));
                        // 延时
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        break;
                    }
                } while (!Thread.currentThread().isInterrupted() && accessTag);
            }
        });
    }

    /**
     * 请求中心网关数据
     * 被动上报
     * 不推荐使用 因主动上报间隔无法确定且response长度无法确定故不推荐使用该方法
     * 如需使用建议仔细核对response数据 必要时需要根据response数据修改数据解析
     *
     * @return 子线程
     */
    Thread GetGateWaySearchThread() {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        // 请求中心网关数据
                        genericConnector.sendGateWaySearch(SensorTagEdit.getText().toString(), new ConnectorListener() {
                            @Override
                            public void onSuccess(boolean b) {
                                // 输出中心网关发送的数据
                                Log.i("Data", genericConnector.GateWayData(genericConnector.getGateWaySearchData().getBytes()));
                                // 将传感器数据显示在SetSensorDataValue
                                SetSensorDataValue(genericConnector.GateWayData(genericConnector.getGateWaySearchData().getBytes()));
                            }

                            @Override
                            public void onFail(Exception e) {

                            }
                        });
                        // 延时
                        TimeUnit.SECONDS.sleep(2);
                    } catch (Exception e) {
                        break;
                    }
                }
                while (!Thread.currentThread().isInterrupted() && accessTag);
            }
        });
    }

    /**
     * 发送中心网关控制指令
     */
    void SendGateWayControlThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Random rand = new Random();
                try {
                    // 发送中心网关控制指令
                    genericConnector.sendGateWayControl(ControlTagEdit.getText().toString(), String.valueOf(rand.nextInt(90000) + 10000), Integer.valueOf(ControlValueEdit.getText().toString()), new ConnectorListener() {
                        @Override
                        public void onSuccess(boolean b) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onFail(Exception e) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    });
                } catch (Exception e) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    /**
     * 解析中心网关Response数据
     *
     * @param data 中心网关Response数据
     * @return 传感器数据
     */
    String GetSensorData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONObject datas = jsonObject.getJSONObject("datas");
            return String.valueOf(datas.optDouble(SensorTagEdit.getText().toString()));
        } catch (JSONException e) {
            return "";
        }
    }

    /**
     * 设置传感器数据控件Value
     *
     * @param data 中心网关Response数据
     */
    void SetSensorDataValue(String data) {
        String buffer = GetSensorData(data);
        System.out.println(buffer);
        if (!Objects.equals(buffer, "NaN")) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    SensorValueText.setText(buffer);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        // 连接按钮事件处理
        if (v.getId() == R.id.LinkButton) {
            if (genericConnector == null) {
                // 读取输入的IP和Port
                gatewayIP = GateWayIPEdit.getText().toString();
                gatewayPort = Integer.parseInt(GateWayPortEdit.getText().toString());

                // 禁用控件
                GateWayIPEdit.setEnabled(false);
                GateWayPortEdit.setEnabled(false);
                SearchSwitch.setEnabled(false);

                // 连接中心网关
                Toast.makeText(this, "正在连接...", Toast.LENGTH_SHORT).show();
                try {
                    genericConnector = new GenericConnector(DataBusFactory.newSocketDataBus(gatewayIP, gatewayPort), new ConnectResultListener() {
                        @Override
                        public void onConnectResult(boolean b) {
                            if (b) {
                                Log.i("GateWayStatus", "Link OK");
                                Toast.makeText(getApplication(), "连接成功", Toast.LENGTH_SHORT).show();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        LinkButton.setText("DISC");
                                    }
                                });
                            } else {
                                Log.i("GateWayStatus", "Link Error");
                                // 销毁
                                genericConnector = null;

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 启用控件
                                        GateWayIPEdit.setEnabled(true);
                                        GateWayPortEdit.setEnabled(true);
                                        SearchSwitch.setEnabled(true);

                                        LinkButton.setText("Link");

                                        Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    });
                } catch (Exception e) {
                    Log.e("Link Error", e.toString());
                    // 销毁
                    genericConnector = null;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            // 启用控件
                            GateWayIPEdit.setEnabled(true);
                            GateWayPortEdit.setEnabled(true);
                            SearchSwitch.setEnabled(true);

                            LinkButton.setText("Link");

                            Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } else {
                if (getSensorDataThread != null) {
                    // 结束线程
                    getSensorDataThread.interrupt();
                    getSensorDataThread = null;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            GetButton.setText("Get");
                            // 启用控件
                            SensorTagEdit.setEnabled(true);
                            GetSingleButton.setEnabled(true);
                            GetContinuousButton.setEnabled(true);
                        }
                    });
                }

                // 销毁
                genericConnector.stopConnect();
                genericConnector = null;

                // 启用控件
                GateWayIPEdit.setEnabled(true);
                GateWayPortEdit.setEnabled(true);
                SearchSwitch.setEnabled(true);

                LinkButton.setText("Link");

                Toast.makeText(this, "已断开连接", Toast.LENGTH_SHORT).show();
            }
        }
        // 获取数据按钮事件处理
        else if (v.getId() == R.id.GetButton) {
            // 获取数据上报方式
            searchTag = SearchSwitch.isChecked();
            // 判断是否建立连接
            if (genericConnector != null) {
                // 判断数据获取方式
                if (accessTag) {
                    // 持续获取 确保线程未使用
                    if (getSensorDataThread == null) {
                        // 判断数据上报方式
                        if (searchTag) {
                            // 初始化数据获取线程
                            getSensorDataThread = GetGateWayResultDataThread();
                            // 开启数据获取线程
                            getSensorDataThread.start();

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    GetButton.setText("Stop");
                                    // 禁用控件
                                    SensorTagEdit.setEnabled(false);
                                    GetSingleButton.setEnabled(false);
                                    GetContinuousButton.setEnabled(false);
                                }
                            });
                        } else {
                            getSensorDataThread = GetGateWaySearchThread();
                            getSensorDataThread.start();
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    GetButton.setText("Stop");
                                    SensorTagEdit.setEnabled(false);
                                    GetSingleButton.setEnabled(false);
                                    GetContinuousButton.setEnabled(false);
                                }
                            });

                        }
                    } else {
                        // 停止线程
                        getSensorDataThread.interrupt();
                        getSensorDataThread = null;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                GetButton.setText("Get");
                                SensorTagEdit.setEnabled(true);
                                GetSingleButton.setEnabled(true);
                                GetContinuousButton.setEnabled(true);
                            }
                        });
                    }
                }
                // 单次获取数据 (Bug:在主动上报环境下需要等待主动上报数据的瞬间获取数据,可以用while等待数据到达,但等待时间不确定故弃用该方法)
                else {
                    if (searchTag) {
                        GetGateWayResultDataThread().start();
                    } else {
                        GetGateWaySearchThread().start();
                    }
                }
            } else {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show();
            }
        }
        // 发送控制指令按钮事件处理
        else if (v.getId() == R.id.SendButton) {
            if (genericConnector != null) {
                SendGateWayControlThread();
            } else {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show();
            }
        }
    }
}